package com.fengye.jpa.converter.converters;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;

import javax.persistence.AttributeConverter;
import java.util.Collections;
import java.util.List;


public class ListAndJsonConverter implements AttributeConverter<List, String>{

    @Autowired
    private ObjectMapper objectMapper;
    @Override
    public String convertToDatabaseColumn(List list) {
        if (list == null) {
            return null;
        }
        try {
            return objectMapper.writeValueAsString(list);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    @SneakyThrows
    @Override
    @SuppressWarnings("unchecked")
    public List convertToEntityAttribute(String s) {
        if (s == null) {
            return Collections.emptyList();
        }
        try {
            return objectMapper.readValue(s, List.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
